package spark.sql

import org.apache.spark.sql.types.StructType

/**
  * Created by yingzhouling on 9/1/17.
  */
object ColumnUtils {
  def getNotExistNameByArray(replaceCol: String, allCols: Seq[String]): String = {
    if (!allCols.contains(replaceCol)) {
      replaceCol
    }
    else {
      val validNames = allCols.filter(!_.equals(replaceCol))
      var extendNum = 1;
      while (!isValid(name(replaceCol, extendNum), validNames)) {
        extendNum += 1
      }
      name(replaceCol, extendNum)
    }
  }

  def getNotExistNameBySchema(replaceCol: String, structType: StructType): String = {
    getNotExistNameByArray(replaceCol, structType.map(_.name))
  }

  private def isValid(colName: String, validNames: Seq[String]) = !validNames.contains(colName)

  private def name(colName: String, extendName: Int) = s"${colName}_${extendName}"
}
